<template>
	<view class="container">
		<uv-toast ref="toast"></uv-toast>
		<view class="free_course_info" v-if="freeCourse.id">
			<text class="name">学习时刻</text>
			<!-- <Tags class="tag" :tags="['免费课程']" bg-color="#f0ad4e" ft-color="#f0ad4e" /> -->
		</view>

		<view class="info">
			<view class="logo"></view>
			<text class="text">观看免费课程即可获取早餐券，每天只可观看一次免费视频</text>
		</view>

		<view class="grid_container">
			<view v-for="(item, index) in gridItems" :key="index" class="item" :class="{ 'empty': !item }"
				@click.stop="handleVideoClick(item, index)">
				<template v-if="item">
					<image class="cover" :src="loading ? '' : item.coverImageUrl" />
					<view class="video_info">
						<text class="duration">{{ formatDuration(item.duration) }}</text>
						<view class="play_icon">
							<uv-icon name="play-right-fill" color="#fff" size="40"></uv-icon>
						</view>
					</view>
					<view v-if="!isLoggedIn || !item.unLocked" class="lock_mask">
						<uv-icon name="lock-fill" color="#fff" size="32"></uv-icon>
						<text class="lock_text">{{ item.statusText }}</text>
					</view>
				</template>
				<template v-else>
					<view class="empty_placeholder">
						<uv-icon name="play-circle" color="#e5e5e5" size="40"></uv-icon>
						<text>敬请期待</text>
					</view>
				</template>
			</view>
		</view>

		<view v-if="showPagination" class="grid_operation">
			<view class="icon_group">
				<view class="page_btn left" :class="{ disabled: isFirstPage }" @click="handlePageChange('prev')">
					<uv-icon name="arrow-left" size="24" :color="isFirstPage ? '#ccc' : '#3c9cff'"></uv-icon>
					<text>上一页</text>
				</view>
				<text class="page_info">{{ mediaRecord.page }}/{{ totalPages }}</text>
				<view class="page_btn right" :class="{ disabled: isLastPage }" @click="handlePageChange('next')">
					<text>下一页</text>
					<uv-icon name="arrow-right" size="24" :color="isLastPage ? '#ccc' : '#3c9cff'"></uv-icon>
				</view>
			</view>
		</view>
	</view>

</template>

<script>
	export default {
		name: "VideoCoverGrid",
		data() {
			return {
				loading: true,
				isLoggedIn: false,
				freeCourse: {
					id: null,
					name: '',
				},
				videoInfos: [],
				mediaRecord: {
					items: [],
					count: 0,
					page: 1,
					pageSize: 9
				}
			};
		},

		computed: {
			hasVideos() {
				return this.videoInfos.length > 0;
			},
			totalPages() {
				return Math.ceil(this.mediaRecord.count / this.mediaRecord.pageSize);
			},
			showPagination() {
				return this.totalPages > 1;
			},
			isFirstPage() {
				return this.mediaRecord.page === 1;
			},
			isLastPage() {
				return this.mediaRecord.page === this.totalPages;
			},
			gridItems() {
				const items = [...this.videoInfos];
				while (items.length < 9) {
					items.push(null);
				}
				return items;
			}
		},

		methods: {
			// 显示提示信息
			showToast(msg, type = 'default', duration = 1000) {
				this.$refs.toast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			formatDuration(seconds) {
				if (!seconds) return '00:00';
				const minutes = Math.floor(seconds / 60);
				const remainingSeconds = Math.floor(seconds % 60);
				return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
			},

			// 检查登录状态
			checkLoginStatus() {
				const token = uni.getStorageSync('token');
				this.isLoggedIn = !!token;
			},

			// 获取锁定文本
			getLockText(item) {
				if (!this.isLoggedIn) return '请先登录';
				if (!item.unLocked && item.watchToday) return '今日已观看';
				return '观看后解锁';
			},

			// 处理视频点击
			async handleVideoClick(item, index) {
				if (!item) {
					return;
				}
				// 检查登录状态
				const token = uni.getStorageSync('token');
				const shopToken = uni.getStorageSync('shop_token');

				// 如果是商家端用户，提示切换到用户端
				if (shopToken && !token) {
					this.showToast('请使用用户端账号观看', 'default', 1000);
					return;
				}

				// 如果未登录，触发登录提示
				if (!token) {
					uni.$emit('NotLogin');
					return;
				}

				if (item && item.unLocked) {
					const today = await this.fetchUserTodayWatch();
					if (today) {
						this.showToast('今日已观看', 'default', 1000);
						return;
					}
				}

				// 检查视频是否可播放
				if (!item.unLocked) {
					if (item.watchToday) {
						this.showToast('今日已观看该视频', 'default', 1000);
					} else {
						this.showToast('请先观看前面的视频', 'default', 1000);
					}
					return;
				}

				// 可以播放，跳转到播放页面
				uni.navigateTo({
					url: `/subpkg/video_play/video_play?courseMediaId=${item.id}&courseId=${item.courseId}`
				});
			},
			// 检查用户今日是否观看
			async fetchUserTodayWatch() {
				try {
					const res = await this.$http.post('/user/video/today');
					return res;
				} catch (e) {
					this.showToast(e.msg);
				}
			},
			async fetchFreeCourse() {
				try {
					this.loading = true;
					const data = await this.$http.get('/course/current/free/course');
					if (data) {
						this.freeCourse = data;
						if (data.mediaRecord) {
							this.mediaRecord = data.mediaRecord;
						}
						await this.fetchCourseVideoInfos();
						// 如果用户已登录，获取可播放视频状态
						if (this.isLoggedIn) {
							await this.fetchAvailableVideos();
						}
					}
				} catch (error) {
					console.error('获取免费课程失败:', error);
					this.showToast('获取课程信息失败', 'error', 1000);
				} finally {
					this.loading = false;
				}
			},

			// 获取可播放视频状态
			async fetchAvailableVideos() {
				try {
					const page = this.mediaRecord.page;
					const size = this.mediaRecord.pageSize;
					// 添加分页参数和课程ID
					const response = await this.$http.get(`/user/video/available?page=${page}&size=${size}`);
					if (response && Array.isArray(response)) {
						// 更新视频解锁状态
						this.videoInfos = this.videoInfos.map(item => {
							// 修改匹配条件，使用 mediaId 而不是 id
							const availableVideo = response.find(v => v.id === item.id);
							if (availableVideo) {
								return {
									...item,
									unLocked: availableVideo.unLocked,
									watchToday: availableVideo.watchToday,
									statusText: availableVideo.statusText
								};
							}

							// 如果找不到对应的可用视频信息，默认为锁定状态
							return {
								...item,
								unLocked: false,
								watchToday: false,
								statusText: '未解锁'
							};
						});
					}
				} catch (error) {
					console.error('获取可播放视频状态失败:', error);
					// 发生错误时，将所有视频设置为锁定状态
					this.videoInfos = this.videoInfos.map(item => ({
						...item,
						unLocked: false,
						watchToday: false
					}));
				}
			},

			// 修改分页方法，在切换页面时同步更新可播放状态
			async handlePageChange(direction) {
				if (
					(direction === 'prev' && this.isFirstPage) ||
					(direction === 'next' && this.isLastPage)
				) {
					return;
				}

				const newPage = direction === 'prev' ?
					this.mediaRecord.page - 1 :
					this.mediaRecord.page + 1;

				try {
					await this.fetchPageData(newPage);
					// 如果用户已登录，获取新页面的可播放视频状态
					if (this.isLoggedIn) {
						await this.fetchAvailableVideos();
					}
				} catch (error) {
					console.error('页面切换失败:', error);
					this.showToast('获取数据失败', 'error', 1000);
				}
			},

			// 获取页面数据的方法
			async fetchPageData(pageNum) {
				try {
					this.loading = true;
					const data = await this.$http.get(
						`/course/free/course/media?courseId=${this.freeCourse.id}&pageNum=${pageNum}&pageSize=${this.mediaRecord.pageSize}`
					);

					if (data) {
						this.mediaRecord = {
							items: data.items || [],
							count: data.count,
							page: pageNum,
							pageSize: this.mediaRecord.pageSize
						};

						await this.fetchCourseVideoInfos();
					}
				} catch (error) {
					console.error('获取分页数据失败:', error);
					this.showToast('获取数据失败', 'error', 1000);
				} finally {
					this.loading = false;
				}
			},

			async fetchCourseVideoInfos() {
				try {
					const videoIds = this.mediaRecord.items
						.map(item => item.videoId)
						.join(',');

					if (!videoIds) {
						this.videoInfos = [];
						return;
					}

					const data = await this.$http.post(
						`/courses/media/batch/video/infos?videoIds=${videoIds}`
					);

					if (data && Array.isArray(data)) {
						const videoInfoMap = data.reduce((map, item) => {
							map[item.videoId] = item;
							return map;
						}, {});

						this.videoInfos = this.mediaRecord.items.map(media => {
							const videoInfo = videoInfoMap[media.videoId] || {};
							return {
								...media,
								coverImageUrl: media.coverImageUrl || videoInfo.coverURL,
								duration: videoInfo.duration || 0
							};
						});
					}
				} catch (error) {
					console.error('获取视频信息失败:', error);
					this.videoInfos = [];
				}
			},

			async initData() {
				this.checkLoginStatus();
				await this.fetchFreeCourse();
				if (this.isLoggedIn && this.freeCourse.id) {
					await this.fetchAvailableVideos();
				}
			}
		},

		created() {
			uni.$on('videoComplete', () => this.fetchAvailableVideos());
			this.initData();
		},

		beforeDestroy() {
			uni.$off('videoComplete');
		}
	}
</script>

<style lang="scss" scoped>
	@import 'VideoCoverGrid.scss';

	.lock_mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		gap: 10rpx;

		.lock_text {
			color: #fff;
			font-size: 24rpx;
		}
	}
</style>